<?php
declare(strict_types=1);

namespace App\Service;

use App\Model\Entity\JnSuppliersUsers;
use App\Model\Entity\JnWmsUserStation;
use phpDocumentor\Reflection\Types\Mixed_;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Db\DB;

/**
 * Class UserStationService
 * @package App\Service
 * @Bean("UserStationService")
 */
class UserStationService {


    public function getUserStations($userId) : array
    {
       $list =  JnWmsUserStation::where('suppliers_user_id' ,$userId )->get();
       return $list ? $list->toArray(): [];
    }

    public function getUserStationCode($userId) : string
    {
        $info = JnWmsUserStation::where('suppliers_user_id' , $userId)->first();
        return $info ? $info->getStationCode() : '';

    }

    /**
     * @param $userId
     * @param $stationCode
     * @return bool
     */
    public function bindOnly($userId ,$stationCode) :bool
    {
        DB::transaction(function()  use ($userId ,$stationCode){
            JnWmsUserStation::where('suppliers_user_id' , $userId)->delete();
            $data = [
                'suppliersUserId'   => $userId ,
                'stationCode'       => $stationCode,
            ];
            JnWmsUserStation::insert($data);
        });

        return true;
    }

    public function getStationUsers($stationCode) :array
    {
        $res = JnWmsUserStation::where('station_code' ,$stationCode ) ->get(['suppliers_user_id']);

        $list = [];
        if ($res) {
            $userIds = array_column($res->toArray() , 'suppliersUserId');
            $list = JnSuppliersUsers::whereIn('id' , $userIds)->get()->toArray();
        }
        return $list;
    }

    public function unBind($userId ,$stationCode) : bool
    {
        $res  = JnWmsUserStation::where('suppliers_user_id' , $userId)
                                ->where('station_code' , $stationCode)
                                ->delete();

        return $res ? true : false;
    }

    /**
     * @param $userId
     * @param $stationCode
     * @return bool
     */
    public function bind($userId ,$stationCode) :bool
    {
        DB::transaction(function()  use ($userId ,$stationCode){
            $info = JnWmsUserStation::select()->where('suppliers_user_id' , $userId)->where('station_code' , $stationCode)->first();
            if (!$info) {
                $data = [
                    'suppliersUserId'   => $userId ,
                    'stationCode'       => $stationCode,
                ];
                $id = JnWmsUserStation::insertGetId($data);
            }else
            {
                $id = $info ['id'];
            }
        });

        return true;
    }

}